﻿using System;
using System.IO;
using System.Windows.Forms;

namespace Latin_Vocabulary_Indicator
{
    public partial class Latin_indicator : Form
    {
        public string inFolder = null;
        public Latin_indicator()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            refresh_folder();
        }

        [System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        private static extern int StrCmpLogicalW(string psz1, string psz2);

        private void refresh_folder()
        {
            folderlist.Items.Clear();
            if (!Directory.Exists("Latin\\")) Directory.CreateDirectory("Latin\\");
            string[] dirs = Directory.GetDirectories("Latin\\", "*", SearchOption.AllDirectories);
            Array.Sort(dirs, StrCmpLogicalW);
            foreach (string dir in dirs)
            {
                ListViewItem item = new ListViewItem();
                item.ImageIndex = 0;
                item.Text = dir.Split('\\')[dir.Split('\\').Length-1].Split('.')[0];
                folderlist.Items.Add(item);
            }

        }

        private void folder_new_Click(object sender, EventArgs e)
        {
            Enabled = false;
            new stringbox("Folder name:",(returned) =>
            {
                Enabled = true;
                Focus();
                if (returned != null)
                {
                    if (Directory.Exists("Latin\\" + returned))  msg("Folder \"" + returned + "\" already exists."); 
                    else
                    {
                        try
                        {
                            Directory.CreateDirectory("Latin\\" + returned);
                            ListViewItem folderIcon = new ListViewItem();
                            folderIcon.ImageIndex = 0;
                            folderIcon.Text = returned;
                            folderlist.Items.Insert(folderlist.SelectedItems.Count == 0 ? folderlist.Items.Count : folderlist.SelectedIndices[folderlist.SelectedIndices.Count - 1] + 1, folderIcon);
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show("Failed to create new folder ("+ returned +"):\r\n" + exc.Message);
                            refresh_folder();
                        }
                    }
                }
            }).Show();
        }

        private void folder_refresh_Click(object sender, EventArgs e)
        {
            refresh_folder();
        }

        private void folder_delete_Click(object sender, EventArgs e)
        {
            if (folderlist.SelectedItems.Count == 0) { Enabled = false; msg("No folder is selected."); }
            else
            {
                Enabled = false;
                new confirmbox(folderlist.SelectedItems.Count == 1 ? "Delete folder: " + folderlist.SelectedItems[0].Text : "Delete " + folderlist.SelectedItems.Count + " folders?", "Delete", (returned) =>
                            {
                                Enabled = true;
                                Focus();
                                if (returned)
                                {
                                    try
                                    {
                                        foreach (ListViewItem item in folderlist.SelectedItems)
                                        {
                                            Directory.Delete("Latin\\" + item.Text,true);
                                            folderlist.Items.Remove(item);
                                        }
                                    }
                                    catch (Exception exc)
                                    {
                                        MessageBox.Show("Failed to delete folder:\r\n" + exc.Message);
                                        refresh_folder();
                                    }
                                }
                            }).Show();
            }
        }

        private void quit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void options_Click(object sender, EventArgs e)
        {
            if (!File.Exists("Latin\\options.ini"))
                fileOperator.textOutput("Latin\\options.ini", "Review point requires: 5\r\nIncreasement per: 1\r\nDecreasement per: 2");
            Enabled = false;
            new option(this).Show();
        }

        private void folderlist_DoubleClick(object sender, EventArgs e)
        {
            if (folderlist.SelectedItems.Count == 1)
            {
                inFolder = folderlist.SelectedItems[0].Text;
                folder.Visible = false;
                folderlist.Visible = false;
                refresh_file();
                manage.Visible = true;
                start.Visible = true;
                filelist.Visible = true;
            }
        }

        public void refresh_file()
        {
            filelist.Items.Clear();
            ListViewItem newitem = new ListViewItem();
            newitem.ImageIndex = 0;
            newitem.Text = "..";
            filelist.Items.Add(newitem);
            string[] files = Directory.GetFiles("Latin\\" + inFolder, "*.lvi", SearchOption.TopDirectoryOnly);
            Array.Sort(files, StrCmpLogicalW);
            foreach (string subfile in files)
            {
                ListViewItem item = new ListViewItem();
                item.ImageIndex = 1;
                string[] temp = subfile.Split('\\')[subfile.Split('\\').Length - 1].Split('.');
                string temp2 = "";
                for(byte x =0;x<= temp.Length - 2; x++)temp2 += temp[x] + (x == temp.Length - 2?null: ".");
                item.Text = temp2;
                filelist.Items.Add(item);
            }
        }

        private void filelist_DoubleClick(object sender, EventArgs e)
        {
            if (filelist.SelectedItems.Count == 1)
            {
                if (filelist.SelectedItems[0].ImageIndex == 0)
                {
                    manage.Visible = false;
                    start.Visible = false;
                    filelist.Visible = false;
                    refresh_folder();
                    folder.Visible = true;
                    folderlist.Visible = true;
                }
                else manage_edit_Click(null, null);
            }
        }

        private void manage_new_Click(object sender, EventArgs e)
        {
            new wordlist(this, null).Show();
            Hide();
        }

        private void manage_delete_Click(object sender, EventArgs e)
        {
            if (filelist.SelectedItems.Count == 0) { Enabled = false;msg("No file is selected."); }
            else
            {
                Enabled = false;
                new confirmbox(filelist.SelectedItems.Count == 1 ? "Delete file: " + filelist.SelectedItems[0].Text : "Delete " + filelist.SelectedItems.Count + " files?", "Delete", (returned) =>
                {
                    Enabled = true; Focus();
                    if (returned)
                    {
                        foreach (ListViewItem item in filelist.SelectedItems)
                        {
                            try
                            {
                                File.Delete("Latin\\" + inFolder + "\\" + item.Text + ".lvi");
                                filelist.Items.Remove(item);
                            }
                            catch (Exception exc)
                            {
                                MessageBox.Show("Failed to delete file (" + item.Text +"):\r\n" + exc.Message);
                                refresh_folder();
                            }
                        }
                    }
                }).Show();
            }

        }
        private void msg(string input)
        {
            Enabled = false; new message(input, () => { Enabled = true; Focus(); }).Show();
        }

        private void manage_edit_Click(object sender, EventArgs e)
        {
            if (filelist.SelectedItems.Count != 1) { msg("Only one file should be selected."); return; }
            new wordlist(this, filelist.SelectedItems[0].Text).Show();
            Hide();
        }

        private void manage_refresh_Click(object sender, EventArgs e)
        {
            refresh_file();
        }

        private void folder_rename_Click(object sender, EventArgs e)
        {
            if (folderlist.SelectedItems.Count !=1) { Enabled = false; msg("Only one folder should be selected."); }
            else
            {
                Enabled = false;
                ListViewItem toRename = folderlist.SelectedItems[0];
                new stringbox("Rename to:", (returned) => {
                    Enabled = true;
                    Focus();
                    if (returned != null)
                    {
                        foreach(ListViewItem item in folderlist.Items)
                        if (item.Text.ToLower() == returned.ToLower())
                            {
                                msg("Folder \"" + item.Text + "\" already exists.");
                                return;
                            }
                        try
                        {
                            Directory.Move("Latin\\" + toRename.Text, "Latin\\" + returned);
                            toRename.Text = returned;
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show("Failed to rename folder ("+ toRename.Text +"):\n"+exc.Message);
                        }
                    }
                }).Show();
            }
        }
        private void startTask(mainproj.testType intertype)
        {
            new confirmbox("Start "+ intertype.ToString() +"?",intertype.ToString(), (returned) => {
                Enabled = true; Focus(); if (returned)
                {

                    if (filelist.Items[0].Selected) filelist.Items[0].Selected = false;
                    if (filelist.SelectedItems.Count == 0) { Enabled = false; msg("No file is selected."); }
                    else
                    {
                        System.Collections.Generic.List<ListViewItem> itemSelection = new System.Collections.Generic.List<ListViewItem>();
                        foreach (ListViewItem fileItem in filelist.SelectedItems)
                        {
                            string[] fileDetail = fileOperator.textInput("Latin\\" + inFolder + "\\" + fileItem.Text + ".lvi").Split('\n');
                            short listNum = 0;
                            foreach (string sub in fileDetail)
                            {
                                ListViewItem newitem = new ListViewItem();
                                newitem.Text = (listNum++).ToString();
                                newitem.SubItems.Add(fileOperator.accentTransform(sub.Split('|')[0].Trim(), true));
                                newitem.SubItems.Add(fileOperator.togglePos(sub.Split('|')[1].Trim()));
                                for (byte x = 2; x <= 3; x++) newitem.SubItems.Add(sub.Split('|')[x].Trim());
                                itemSelection.Add(newitem);
                            }
                        }
                        string henText = "";
                        for (byte x = 0; x <= filelist.SelectedItems.Count - 1; x++) henText += filelist.SelectedItems[x].Text + (x == filelist.SelectedItems.Count - 1 ? null : " + ");
                        if (henText.Length > 40) henText = filelist.SelectedItems[0].Text + "... (" + filelist.SelectedItems.Count + ")";
                        var temp = new mainproj(this, itemSelection.ToArray(), intertype, henText); temp.Show(); temp.Focus();
                        Hide();
                    }


                }
            }).Show();
        }
        private void start_review_Click(object sender, EventArgs e)
        {
            startTask(mainproj.testType.review);
        }

        private void start_test_Click(object sender, EventArgs e)
        {
            startTask(mainproj.testType.test);
        }

        private void Latin_indicator_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
    }
}
